package com.why.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.why.entity.Admin;
import com.why.entity.Students;
import com.why.entity.Teachers;
import com.why.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户表(Admin)表控制层
 *
 * @author makejava
 * @since 2023-05-01 17:23:14
 */
@RestController
@CrossOrigin
@RequestMapping("/admin")
public class AdminController {
    /**
     * 服务对象
     */
    @Autowired
    private AdminService adminService;

    /**
     * 登录
     *
     * @param request
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public String Login(HttpServletRequest request, @RequestBody Admin admin) {
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<Admin>();
        queryWrapper.eq(Admin::getUsername, admin.getUsername()).eq(Admin::getPassword, admin.getPassword());
        Admin user = adminService.getOne(queryWrapper);
        if (user == null) {
            return "error";
        } else {
            request.getSession().setAttribute("adminId", user.getId());
            return "success";
        }
    }

    /**
     * 退出登录，清楚session
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public String Logout(HttpServletRequest request) {
        request.getSession().removeAttribute("adminId");
        return "success";
    }

    /**
     * 获取登录admin的信息
     *
     * @return
     */
    @GetMapping("/getadmin")
    public Admin getAdmin(HttpServletRequest request) {
        Long id = (Long) request.getSession().getAttribute("adminId");
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<Admin>();
        queryWrapper.eq(Admin::getId, id);
        Admin admin = adminService.getOne(queryWrapper);
        return admin;
    }


    /**
     * 修改个人信息
     *
     * @param admin
     * @param request
     * @return
     */
    @PostMapping("/update")
    public String update(@RequestBody Admin admin, HttpServletRequest request) {
        Long adminId = (Long) request.getSession().getAttribute("adminId");
        LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<Admin>();
        queryWrapper.eq(Admin::getId, adminId);
        adminService.update(admin, queryWrapper);
        return "success";
    }


}

